package team.pikachu.pikachuclient.message;

import android.content.Context;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.Toast;

import com.google.gson.Gson;

import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import team.pikachu.pikachuclient.R;
import team.pikachu.pikachuclient.beans.Location;
import team.pikachu.pikachuclient.beans.temp.MessageTemp;
import team.pikachu.pikachuclient.utils.Constants;
import team.pikachu.pikachuclient.utils.HttpUtils;
import team.pikachu.pikachuclient.utils.IPConstants;
import team.pikachu.pikachuclient.utils.JsonUtils;
import team.pikachu.pikachuclient.utils.LogUtil;

public class MsgUploadActivity extends AppCompatActivity {
    private static final String LOGTAG = LogUtil.makeLogTag(MsgUploadActivity.class);

    private SharedPreferences pre;

    @BindView(R.id.event_name)
    EditText eventNameText;
    @BindView(R.id.location_id)
    AutoCompleteTextView locationIdText;
    @BindView(R.id.room)
    EditText roomText;
    @BindView(R.id.detail)
    EditText detailText;
    @BindView(R.id.toolbar)
    Toolbar toolbar;

    private String eventName;
    private String room;
    private String detail;
    private String location;
    private int locationId;
    private int userId;
    private int roleId;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_msg_upload);
        ButterKnife.bind(this);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        pre = getSharedPreferences("userInfo", Context.MODE_PRIVATE);

        LocationAsy locationAsy = new LocationAsy();
        String locationPath = IPConstants.GET_LOCATIONS + pre.getInt(getString(R.string.pre_schoolid), 0);
        locationAsy.execute(locationPath);

        locationIdText.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Location location = (Location) parent.getItemAtPosition(position);
                String name = location.getLocation();
                locationIdText.setText(name);
                locationIdText.setSelection(name.length());
                locationId = location.getId();
            }
        });

    }

    @OnClick(R.id.submit)
    void onSubmit() {
        eventName = eventNameText.getText().toString();
        room = roomText.getText().toString();
        location = locationIdText.getText().toString();
        detail = detailText.getText().toString();
        userId = pre.getInt(getString(R.string.pre_userid), 0);
        roleId = pre.getInt(getString(R.string.pre_roleid), 1);

        View focusView = null;
        Boolean cancel = false;

        if (TextUtils.isEmpty(eventName)) {
            eventNameText.setError("请输入故障简介");
            focusView = eventNameText;
            cancel = true;
        } else if (TextUtils.isEmpty(location)) {
            locationIdText.setError("请输入故障地点");
            focusView = locationIdText;
            cancel = true;
        }

        if (cancel) {
            focusView.requestFocus();
            return;
        } else {
            if (locationId == 0){
                room = location + " " + room;
            }
            MessageTemp msg = new MessageTemp(eventName, locationId, room, detail, Constants.STATUS_WAITING, userId, roleId, Constants.OP_UPLOAD);

            Gson gson = new Gson();
            String json = gson.toJson(msg);
            Log.d(LOGTAG, json);

            UploadAsy uploadAsy = new UploadAsy();
            uploadAsy.execute(IPConstants.ACCEPT, json);
        }
    }

    //数据上传异步
    public class UploadAsy extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            return HttpUtils.sendJson(params[0], params[1]);
        }

        @Override
        protected void onPostExecute(String aBoolean) {
            super.onPostExecute(aBoolean);
            if (aBoolean.equals("success")) {
                Log.d(LOGTAG, "success");
                Toast.makeText(MsgUploadActivity.this, "发送信息成功", Toast.LENGTH_SHORT).show();
                finish();
            } else {
                Log.d(LOGTAG, "fail");
                Toast.makeText(MsgUploadActivity.this, "发送信息失败", Toast.LENGTH_SHORT).show();

            }
        }

    }


    /**
     * 地址名自动补全
     * 适配器适配地址名字List
     */
    private class LocationAsy extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            return HttpUtils.sendPostMethod(params[0]);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
//            Log.d(LOGTAG,s);
            if (!s.equals(getString(R.string.timeout)) && !s.equals(getString(R.string.request_failed))) {

                Location[] locations = JsonUtils.readValue(s, Location[].class);

                assert locations != null;
                for (Location location : locations) {
                    Log.i(LOGTAG, location.toString());
                }

                List<Location> locationList = Arrays.asList(locations);
                LocationAdapter arrayAdapter = new LocationAdapter(MsgUploadActivity.this, android.R.layout.simple_list_item_1, locationList);
                arrayAdapter.setOnCompleteListener(new LocationAdapter.CompleteListener() {
                    @Override
                    public void onComplete(Location location) {
                        locationId = location.getId();
                    }
                });
                locationIdText.setAdapter(arrayAdapter);

            }
        }
    }


}
